<template>
  <view class="page">
    <!-- 统计卡片 -->
    <view class="stats">
      <view class="stat-item waiting">
        <text class="stat-value">{{ stats.waiting_count || 0 }}</text>
        <text class="stat-label">等待中</text>
      </view>
      <view class="stat-item available">
        <text class="stat-value">{{ stats.available_count || 0 }}</text>
        <text class="stat-label">可借阅</text>
      </view>
      <view class="stat-item cancelled">
        <text class="stat-value">{{ stats.cancelled_count || 0 }}</text>
        <text class="stat-label">已取消</text>
      </view>
    </view>

    <!-- 标签栏 -->
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="['tab-item', activeTab === tab.value ? 'active' : '']"
        @click="switchTab(tab.value)"
      >
        {{ tab.label }}
        <text class="tab-count" v-if="getTabCount(tab.value) > 0">({{ getTabCount(tab.value) }})</text>
      </view>
    </view>

    <!-- 预约列表 -->
    <view class="content">
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else-if="reservationList.length === 0" class="empty">
        <image src="/static/img/empty.png" class="empty-img" mode="aspectFit"></image>
        <text class="empty-text">暂无预约记录</text>
      </view>
      <view v-else class="list">
        <view v-for="item in reservationList" :key="item.id" class="reservation-item">
          <image :src="item.cover || '/static/img/default-item.png'" class="book-cover" mode="aspectFill"></image>
          <view class="book-info">
            <text class="book-name">{{ item.book_name }}</text>
            <text class="book-author">作者：{{ item.author }}</text>
            <text class="reserve-date">预约时间：{{ formatDate(item.reservation_date) }}</text>
            <text class="expiry-date">过期时间：{{ formatDate(item.expiry_date) }}</text>
            <view class="status-row">
              <view :class="['status', getStatusClass(item.status)]">
                {{ getStatusText(item.status) }}
              </view>
              <view class="queue-info" v-if="item.status === 'waiting'">
                排队中
              </view>
            </view>
          </view>
          <view class="actions">
            <button 
              v-if="item.status === 'waiting'" 
              class="cancel-btn" 
              @click="handleCancelReservation(item)"
            >
              取消预约
            </button>
            <button 
              v-if="item.status === 'available'" 
              class="borrow-btn" 
              @click="handleBorrowReserved(item)"
            >
              前往借阅
            </button>
            <view v-if="item.status === 'cancelled'" class="finished">
              已取消
            </view>
            <view v-if="item.status === 'expired'" class="finished">
              已过期
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 下拉刷新提示 -->
    <view v-if="refreshing" class="refresh-tip">
      正在刷新...
    </view>
  </view>
</template>

<script>
import { myRequest } from '@/util/request.js';

export default {
  name: 'ReservationList',
  data() {
    return {
      activeTab: '',
      tabs: [
        { label: '全部', value: '' },
        { label: '等待中', value: 'waiting' },
        { label: '可借阅', value: 'available' },
        { label: '已完成', value: 'cancelled,expired' }
      ],
      reservationList: [],
      stats: {},
      loading: false,
      refreshing: false
    };
  },
  onLoad() {
    this.fetchReservations();
    this.loadStats();
  },
  onShow() {
    // 从其他页面返回时刷新数据
    this.fetchReservations();
    this.loadStats();
  },
  onPullDownRefresh() {
    this.refreshing = true;
    Promise.all([
      this.fetchReservations(),
      this.loadStats()
    ]).finally(() => {
      this.refreshing = false;
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    async fetchReservations() {
      this.loading = true;
      try {
        const data = await myRequest({
          url: '/api/reservations/my-reservations',
          method: 'GET',
          data: {
            status: this.activeTab
          }
        });
        this.reservationList = Array.isArray(data) ? data : [];
      } catch (e) {
        console.error('获取预约列表失败', e);
        uni.showToast({ title: '获取预约列表失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    async loadStats() {
      try {
        const allReservations = await myRequest({
          url: '/api/reservations/my-reservations',
          method: 'GET'
        });
        
        if (Array.isArray(allReservations)) {
          this.stats = {
            waiting_count: allReservations.filter(r => r.status === 'waiting').length,
            available_count: allReservations.filter(r => r.status === 'available').length,
            cancelled_count: allReservations.filter(r => ['cancelled', 'expired'].includes(r.status)).length
          };
        }
      } catch (e) {
        console.error('获取统计数据失败', e);
      }
    },

    switchTab(value) {
      this.activeTab = value;
      this.fetchReservations();
    },

    async handleCancelReservation(item) {
      uni.showModal({
        title: '取消预约',
        content: `确定要取消《${item.book_name}》的预约吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({
                url: `/api/reservations/${item.id}/cancel`,
                method: 'POST'
              });
              uni.showToast({ title: '预约已取消', icon: 'success' });
              this.fetchReservations();
              this.loadStats();
            } catch (e) {
              console.error('取消预约失败', e);
              uni.showToast({ title: e.message || '取消失败', icon: 'none' });
            }
          }
        }
      });
    },

    handleBorrowReserved(item) {
      uni.showModal({
        title: '预约可借',
        content: `您预约的《${item.book_name}》已可借阅，请在3天内前往图书馆借阅。`,
        confirmText: '我知道了',
        showCancel: false,
        success: () => {
          // 可以跳转到图书详情页
          uni.navigateTo({
            url: `/pages/bookInfo/bookInfo?id=${item.book_id}`
          });
        }
      });
    },

    getStatusText(status) {
      const statusMap = {
        'waiting': '等待中',
        'available': '可借阅',
        'cancelled': '已取消',
        'expired': '已过期'
      };
      return statusMap[status] || status;
    },

    getStatusClass(status) {
      const classMap = {
        'waiting': 'warning',
        'available': 'success',
        'cancelled': 'info',
        'expired': 'danger'
      };
      return classMap[status] || 'info';
    },

    getTabCount(tabValue) {
      if (tabValue === '') {
        return this.stats.waiting_count + this.stats.available_count + this.stats.cancelled_count;
      } else if (tabValue === 'waiting') {
        return this.stats.waiting_count;
      } else if (tabValue === 'available') {
        return this.stats.available_count;
      } else if (tabValue === 'cancelled,expired') {
        return this.stats.cancelled_count;
      }
      return 0;
    },

    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.page {
  background: #f5f5f5;
  min-height: 100vh;
}

.stats {
  display: flex;
  background: #fff;
  margin-bottom: 20rpx;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  position: relative;
}

.stat-item:not(:last-child):after {
  content: '';
  position: absolute;
  right: 0;
  top: 20rpx;
  bottom: 20rpx;
  width: 1rpx;
  background: #eee;
}

.stat-item.waiting .stat-value {
  color: #ff9900;
}

.stat-item.available .stat-value {
  color: #52c41a;
}

.stat-item.cancelled .stat-value {
  color: #999;
}

.stat-value {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  line-height: 1;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

.tabs {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #3E88F0;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #3E88F0;
  border-radius: 2rpx;
}

.tab-count {
  font-size: 20rpx;
  color: #999;
}

.content {
  padding: 20rpx;
}

.loading, .empty {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-img {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.reservation-item {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.book-cover {
  width: 120rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.book-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.3;
}

.book-author {
  font-size: 26rpx;
  color: #666;
}

.reserve-date,
.expiry-date {
  font-size: 24rpx;
  color: #888;
}

.status-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-top: 10rpx;
}

.status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: #fff;
}

.status.success {
  background: #52c41a;
}

.status.warning {
  background: #ff9900;
}

.status.info {
  background: #999;
}

.status.danger {
  background: #ff4d4f;
}

.queue-info {
  font-size: 22rpx;
  color: #666;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
}

.cancel-btn {
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  background: #ff4d4f;
  color: #fff;
  border-radius: 20rpx;
  border: none;
}

.borrow-btn {
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  background: #52c41a;
  color: #fff;
  border-radius: 20rpx;
  border: none;
}

.finished {
  font-size: 24rpx;
  color: #999;
}

.refresh-tip {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 8rpx;
  font-size: 26rpx;
}
</style>
